package cn.mengfly.testnrz.im.server.handler;

import cn.mengfly.testnrz.im.client.InvalidFrameException;
import cn.mengfly.testnrz.im.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Mengfly
 */
@ChannelHandler.Sharable
public class ServerExceptionHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof InvalidFrameException) {
            System.out.println(cause.getMessage());
            ServerSession.closeSession(ctx);
        } else {
            System.out.println(cause.getMessage());
            ctx.close();
        }
    }

    /**
     * 通道读取完成 做刷新操作
     *
     * @param ctx ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ServerSession.closeSession(ctx);
    }
}
